package com.epoint.mobileoa.ui.backup;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.DateHelp;
import com.epoint.mobileoa.tools.IOHelp;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.ui.init.InitView;

/**
 * @author liyc
 * @time 2012-2-13 上午11:30:58
 * @annotation 备份还原
 */
public class BackupView extends SuperView {

	private ListView lv_backup;
	private Button btClean,btBackup;
	private List<Map<String, Object>> mData;
	private String backup_db_path;

	@Override
	public void initControls() {
		backup_db_path = "/"+InitView.MobileOaMainStoreFolder+"/"+getString(R.string.sdforder)+"/backupdb";
		lv_backup = (ListView) findViewById(R.id.lvBackup);
		btClean = (Button) findViewById(R.id.backup_btClean);
		btBackup = (Button) findViewById(R.id.backup_btBackup);
		lv_backup.setOnItemLongClickListener(this);
		btClean.setOnClickListener(this);
		btBackup.setOnClickListener(this);
		IOHelp.FoldCreate(backup_db_path);
		refreshData();
	}

	@Override
	public void refresh(Object... param) {

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position1, long id) {
		final int fileposition = position1;
		LayoutInflater inflater = LayoutInflater.from(this);
		LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.attachmanager_longclickdialog, null);
		final ListView lv = (ListView) ll.findViewById(R.id.al_lv);
		String[] s = {"重命名","删除","还原数据","属性"};
		ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,s);
		lv.setAdapter(aa);
		final AlertDialog.Builder ab = new AlertDialog.Builder(BackupView.this);
		ab.setIcon(R.drawable.epoint2);
		ab.setTitle("操作");
		ab.setView(ll);
		final AlertDialog ad = ab.create();
		ad.show();

		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ad.dismiss();
				switch(position){
				case 0:
					LayoutInflater inflater2 = LayoutInflater.from(BackupView.this);
					LinearLayout ll = (LinearLayout) inflater2.inflate(R.layout.alertinput_editview, null);
					final EditText et = (EditText) ll.findViewById(R.id.ai_et);
					et.setText(mData.get(fileposition).get("title").toString());
					new AlertDialog.Builder(BackupView.this)
					.setIcon(R.drawable.epoint2)
					.setTitle("重命名")
					.setView(ll)
					.setPositiveButton("保存", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							String path = mData.get(fileposition).get("path").toString();
							String prefiledir = path.substring(0,path.lastIndexOf("/"));
							File f = new File(mData.get(fileposition).get("path").toString());
							f.renameTo(new File(prefiledir+"/"+et.getText().toString()));
							refreshData();
						}
					})
					.setNegativeButton("取消", null)
					.create().show();
					break;
				case 1:
					class DialogListener implements
					android.content.DialogInterface.OnClickListener {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							File file = new File(mData.get(fileposition).get("path").toString());
							if (file.exists()) {
								file.delete();
							}
							refreshData();
						}
					}

					TextView tv = new TextView(BackupView.this);
					tv.setTextColor(Color.YELLOW);
					tv.setTextSize(18);
					Spanned source = Html
							.fromHtml("<font color=white>确认删除文件<br/></font><font color=red>"
									+ mData.get(fileposition).get("title").toString()
									+ "</font><br/><font color=white>？</font>");
					tv.setText(source);
					AlertDialog ad = new AlertDialog.Builder(BackupView.this)
					.setIcon(R.drawable.epoint2)
					.setTitle("提示").setView(tv).setPositiveButton("是",
							new DialogListener()).setNegativeButton(
									"否", null).create();
					ad.show();
					break;
				case 2:
					AlertHelp.ShowAlert(BackupView.this, "确认还原数据"+mData.get(fileposition).get("title")+"？",new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							File f = new File(getString(R.string.dbpath)+getString(R.string.dbname));
							f.delete();
							try {
								IOHelp.copyFile(mData.get(fileposition).get("path").toString(), getString(R.string.dbpath)+getString(R.string.dbname));
								ToastHelp.showToastCommon(BackupView.this, "还原成功，软件将重新启动！");
								Intent intent = new Intent(BackupView.this, InitView.class);
								startActivity(intent);
								fp.init();
							} catch (IOException e) {
								ToastHelp.showToastCommon(BackupView.this, "还原失败！");
								e.printStackTrace();
							}
						}
					});

					break;
				case 3:
					File f = new File(mData.get(fileposition).get("path").toString());
					AlertHelp.showFileAttributeAlert(BackupView.this, f);
					break;
				}
			}
		});
		return super.onItemLongClick(parent, view, position1, id);
	}

	@Override
	public void onClick(View v) {
		if(v==btClean){
			AlertHelp.ShowAlert(this, "确认清空所有备份数据吗？", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					File file = new File(backup_db_path);
					File[] files = file.listFiles();
					for(File f:files){
						f.delete();
					}
					refreshData();
					ToastHelp.showToastCommon(BackupView.this, "清空完毕！");
				}
			});
		}
		else if(v==btBackup){
			LayoutInflater inflater = LayoutInflater
					.from(this);
			LinearLayout ll = (LinearLayout) inflater.inflate(
					R.layout.alertinput_editview, null);
			final EditText et = (EditText) ll
					.findViewById(R.id.ai_et);
			new AlertDialog.Builder(this)
			.setIcon(R.drawable.epoint2)
			.setTitle("输入备份名")
			.setView(ll)
			.setPositiveButton("确认", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(StringHelp.isEditTextBlank(et)){
						ToastHelp.showToastCommon(BackupView.this, "名称不能为空！");
						try { 
							Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); 
							field.setAccessible(true); 
							field.set(dialog, false);
						} catch (Exception e) { 
							e.printStackTrace(); 
						} 
					}
					else{
						try{
							IOHelp.copyFile(getString(R.string.dbpath)+getString(R.string.dbname), backup_db_path+"/"+et.getText()+"("+DateHelp.convertDate(new Date(), "yyyy-MM-dd")+")");
							refreshData();
							ToastHelp.showToastCommon(BackupView.this, "备份成功！");
						}catch(Exception e){
							e.printStackTrace();
							ToastHelp.showToastCommon(BackupView.this, "备份失败！");
						}
						try {
							Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
							field.setAccessible(true);
							field.set(dialog, true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			})
			.setNegativeButton("取消", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			})
			.create()
			.show();
		}

	}

	public void refreshData() {
		mData = getData(backup_db_path);
		MyAdapter adapter = new MyAdapter(this);
		lv_backup.setAdapter(adapter);
	}

	private List<Map<String, Object>> getData(String dir) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();

		File file = new File(dir);

		File[] files = file.listFiles();
		for (File currentFile : files) {
			map = new HashMap<String, Object>();
			map.put("path", currentFile.getAbsolutePath());
			map.put("title", currentFile.getName());
			Long time = currentFile.lastModified();
			// 格式化时间字符串
			String timestr = DateFormat.format("yyyy.MM.dd kk:mm:ss", time)
					.toString();
			map.put("info", timestr);
			map.put("icon", R.drawable.img_file_48);
			list.add(map);
		}

		//		File[] files = file.listFiles();//所有文件夹

		/*for (File currentFile : files) {
			if(currentFile.isDirectory()){
				File[] subfiles = currentFile.listFiles();
				for(File subfile:subfiles){
					if(!subfile.isDirectory()){
						map = new HashMap<String, Object>();
						map.put("path", subfile.getAbsolutePath());
						map.put("title", subfile.getName());
						Long time = subfile.lastModified();
						// 格式化时间字符串
						String timestr = DateFormat.format("yyyy.MM.dd kk:mm:ss", time)
								.toString();
						map.put("info", timestr);
						map.put("icon", R.drawable.img_file_48);

						list.add(map);
					}
				}
			}
		}*/
		return list;
	}

	public final class ViewHolder {
		public ImageView iv;
		public TextView tv;
	}

	class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.lv_attach,
						null);
				holder.iv = (ImageView) convertView
						.findViewById(R.id.lv_attach_iv);
				holder.tv = (TextView) convertView
						.findViewById(R.id.lv_attach_tv);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.iv.setBackgroundResource((Integer) mData.get(position)
					.get("icon"));
			final String fileName = (String) mData.get(position).get("title");
			holder.tv.setText(fileName);
			holder.tv.setTextSize(25);
			return convertView;
		}
	}

	@Override
	public int getLayoutInt() {
		return R.layout.backup;
	}

	@Override
	public String setTitle() {
		return getString(R.string.bfhy);
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param){
	}
}
